package com.xxxx.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.xxxx.server.pojo.*;
import com.xxxx.server.service.*;
import com.xxxx.server.vo.PageBean;
import com.xxxx.server.vo.RespBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 学海无涯
 * @since 2021-11-15
 */
@RestController
@RequestMapping("/employee/basic")
@Api(tags = "员工管理")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPoliticsStatusService politicsStatusService;
    @Autowired
    private IJoblevelService joblevelService;
    @Autowired
    private INationService nationService;
    @Autowired
    private IPositionService positionService;
    @Autowired
    private IDepartmentService departmentService;

    @ApiOperation("查询所有员工(分页)")
    @GetMapping("")
    public RespBean<PageBean> getAllEmployee(@RequestParam(defaultValue = "1") Integer currentPage,
                                   @RequestParam(defaultValue = "10") Integer pageSize,
                                   Employee employee,
                                   LocalDate[] beginDataScope){
        PageBean pageBean = employeeService.getAllEmployee(currentPage,pageSize,employee,beginDataScope);
        return new RespBean<PageBean>().success("ok",pageBean);
    }

    @ApiOperation("添加员工")
    @PostMapping("")
    public RespBean addEmp(@RequestBody Employee employee){
       return employeeService.addEmp(employee);
    }

    @ApiOperation("更新员工")
    @PutMapping("")
    public RespBean updateEmp(@RequestBody Employee employee){
        if (employeeService.updateById(employee)){
            return new RespBean().success("更新成功！");
        }
        return new RespBean().error("更细失败！");
    }

    @ApiOperation("删除员工")
    @DeleteMapping("/{id}")
    public RespBean delEmp(@PathVariable Integer id){
        if (employeeService.removeById(id)){
            return new RespBean().success("删除成功！");
        }
        return new RespBean().error("删除失败！");
    }

    @ApiOperation("获取所有政治面貌")
    @GetMapping("politicsStatus")
    public List<PoliticsStatus> getAllPoliticsStatus(){
        return politicsStatusService.list();
    }

    @ApiOperation("获取所有职称")
    @GetMapping("joblevel")
    public List<Joblevel> getAllJoblevel(){
        return joblevelService.list();
    }

    @ApiOperation("获取所有民族")
    @GetMapping("nation")
    public List<Nation> getAllNation(){
        return nationService.list();
    }

    @ApiOperation("获取所有职位")
    @GetMapping("position")
    public List<Position> getAllPosition(){
        return positionService.list();
    }

    @ApiOperation("获取所有部门")
    @GetMapping("department")
    public List<Department> getAllDepartment(){
        return departmentService.getAllDepartment();
    }

    @ApiOperation("获取工号")
    @GetMapping("maxWorkID")
    public RespBean getMaxWorkID(){
        return employeeService.getMaxWorkID();
    }

    @ApiOperation("导出员工数据")
    @GetMapping(value = "export",produces = "application/octet-stream")
    public void exportEmp(HttpServletResponse response){
        List<Employee> employees = employeeService.getEmployee(null);
        // HSSF 是03版excel，导出速度快，兼容性好
        ExportParams params = new ExportParams("员工表","员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, employees);
        ServletOutputStream out = null;
        try {
            // 流形式
            response.setHeader("content-type","application/octet-stream");
            // 防止中文乱码
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("员工表.xls","UTF-8"));
            out = response.getOutputStream();
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (out!=null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @ApiOperation("导入员工数据")
    @PostMapping("import")
    public RespBean importEmp(MultipartFile file){
        ImportParams params = new ImportParams();
        // 去掉标题行
        params.setTitleRows(1);
        List<Nation> nationList = nationService.list();
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        List<Joblevel> joblevelList = joblevelService.list();
        List<Position> positionList = positionService.list();
        List<Department> departmentList = departmentService.list();
        try {
            List<Employee> employeeList = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
            employeeList.forEach(e->{
                Integer nationId = nationList.get(nationList.indexOf(new Nation(e.getNation().getName()))).getId();
                Integer psId = politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(e.getPoliticsStatus().getName()))).getId();
                Integer joblevelId = joblevelList.get(joblevelList.indexOf(new Joblevel(e.getJoblevel().getName()))).getId();
                Integer positionId = positionList.get(positionList.indexOf(new Position(e.getPosition().getName()))).getId();
                Integer departmentId = departmentList.get(departmentList.indexOf(new Department(e.getDepartment().getName()))).getId();
                e.setNationId(nationId);
                e.setPoliticId(psId);
                e.setJobLevelId(joblevelId);
                e.setPosId(positionId);
                e.setDepartmentId(departmentId);
            });
            if (employeeService.saveBatch(employeeList)){
                return new RespBean().success("导入成功！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new RespBean().error("导入失败！");
    }
}
